const fs = require('fs');
const path = require('path');
const rm = require('rimraf');
const got = require('got');
const spinner = require('./spinner');
const chalk = require('chalk');
const startCode = '100000';
const getUrl = (code) => {
  return `https://geo.datav.aliyun.com/areas_v2/bound/${code}.json`;
};
const getFullUrl = (code) => {
  return `https://geo.datav.aliyun.com/areas_v2/bound/${code}_full.json`;
};

spinner.start('starting download geoJson...');

//创建文件夹目录
const dirPath = path.join(__dirname, '../dist');
rm(dirPath, async (error) => {
  if (error) throw error;
  fs.mkdirSync(dirPath);
  spinner.success('end mkdir dist');
  spinner.start('starting download...\n');
  const geos = [];
  const buildGeos = async (code, geo, geos) => {
    if (!geo) return;
    fs.writeFileSync(
      `${dirPath}/${code}.geo.json`,
      JSON.stringify(geo) + '\n',
      { encoding: 'utf-8' }
    );
    while (geo.features && geo.features.length > 0) {
      const f = geo.features.shift();
      if (f.properties.adcode == code) continue;
      let prop = {
        name: f.properties.name,
        adcode: f.properties.adcode,
        level: f.properties.level,
        childrenNum: f.properties.childrenNum,
      };
      if (f.properties.parent) {
        prop.parent = f.properties.parent;
      }
      geos.push(prop);
      prop.children = [];
      spinner.text(`start download ${prop.adcode}...`);
      try {
        if (prop.childrenNum > 0) {
          const { body } = await got.get(getFullUrl(prop.adcode), {
            responseType: 'json',
          });
          await buildGeos(prop.adcode, body, prop.children);
        } else {
          const { body } = await got.get(getUrl(prop.adcode), {
            responseType: 'json',
          });
          fs.writeFileSync(
            `${dirPath}/${prop.adcode}.geo.json`,
            JSON.stringify(body) + '\n',
            { encoding: 'utf-8' }
          );
        }
      } catch (error) {
        console.error(chalk.red(error));
      }
    }
  };
  spinner.text(`start download ${startCode}...`);
  const { body } = await got.get(getFullUrl(startCode), {
    responseType: 'json',
  });
  await buildGeos(startCode, body, geos);
  fs.writeFileSync(
    `${dirPath}/${startCode}.geos.json`,
    JSON.stringify(geos, null, '\t') + '\n',
    { encoding: 'utf-8' }
  );
  console.log('\n\n');
  spinner.successStop('end download geoJson');
});
